from qcloud_cos import CosConfig, CosS3Client
from qcloud_cos.cos_exception import CosServiceError
import os
from typing import Optional
import random
import string

# 从环境变量获取配置
TENCENT_SECRET_ID = os.getenv(
    "TENCENT_SECRET_ID", "AKID53qPlurhXDh2CD7B49B5oNmzAKLD0jQy"
)
TENCENT_SECRET_KEY = os.getenv("TENCENT_SECRET_KEY", "UmspaBhNDwZ3MUREwVs574saAaqvpbEi")
COS_REGION = os.getenv("COS_REGION", "ap-shanghai")
COS_BUCKET_NAME = os.getenv("COS_BUCKET_NAME", "zq4-1318886512")


# 初始化COS客户端
config = CosConfig(
    Region=COS_REGION, SecretId=TENCENT_SECRET_ID, SecretKey=TENCENT_SECRET_KEY
)
cos_client = CosS3Client(config)


def get_presigned_upload_url(key: str, expires_in: int = 60) -> Optional[str]:
    try:
        url = cos_client.get_presigned_url(
            Method="PUT",
            Bucket=COS_BUCKET_NAME,
            Key=key,
            Expired=expires_in,
        )
        return url
    except CosServiceError as e:
        print(f"Error generating presigned upload URL: {e}")
        return None


def get_presigned_download_url(key: str, expires_in: int = 60) -> Optional[str]:
    try:
        url = cos_client.get_presigned_url(
            Method="GET", Bucket=COS_BUCKET_NAME, Key=key, Expired=expires_in
        )
        return url
    except CosServiceError as e:
        print(f"Error generating presigned download URL: {e}")
        return None


def check_file_exists(key: str) -> bool:
    try:
        cos_client.head_object(Bucket=COS_BUCKET_NAME, Key=key)
        return True
    except CosServiceError as e:
        if e.get_status_code() == 404:
            return False
        print(f"Error checking file existence: {e}")
        return False


def generate_random_string_in(length: int = 64) -> str:
    """生成指定长度的随机字符串"""
    letters = string.ascii_letters + string.digits
    return "".join(random.choice(letters) for _ in range(length))


if __name__ == "__main__":
    print(get_presigned_download_url("x1YZlopAu7sb987iaSgmJEaoX4y2jxEB"))
